package agents;

import java.util.Comparator;
import java.util.Map.Entry;


public class AverageUtility {

	public static class UtilityComparator implements Comparator<Entry<?, AverageUtility>> {
		final static int INCREASING = 1;
		final static int DECREASING = -1;
		
		public int order;
		
		public UtilityComparator(int order) {
			this.order = order;
		}
		
		@Override
		public int compare(Entry<?, AverageUtility> o1, Entry<?, AverageUtility> o2) {
			if (o1.getValue().getAverageUtility() < o2.getValue().getAverageUtility())
				return -order;
			if (o1.getValue().getAverageUtility() > o2.getValue().getAverageUtility())
				return order;
			return o1.getValue().getSteps() + order * o2.getValue().getSteps();		
		}		
	}
	
	
	public static final UtilityComparator INCREASING_UTILITY_COMPARATOR =
			new UtilityComparator(UtilityComparator.INCREASING);
	public static final UtilityComparator DECREASING_UTILITY_COMPARATOR =
			new UtilityComparator(UtilityComparator.DECREASING);
	
	private double utility;
	private int steps;
	
	
	public AverageUtility() {
		utility = 0d;
		steps   = 0;
	}
	
	
	public void increaseUtility(double utility) {
		this.utility += utility;
		this.steps++;
	}
	
	public double getAverageUtility() {
		return (steps == 0) ? 0d : utility / steps;
	}
	
	public int getSteps() {
		return steps;
	}
	
	public void clear() {
		utility = 0d;
		steps   = 0;
	}
	
	@Override
	public String toString() {
		return utility + "/" + steps;
	}
}
